package catgory.FolderSize;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * describe:
 *
 * @author huxingjie
 * @date 2019/04/19
 * @since 3.6
 */
public class FileSize {

    private final static ForkJoinPool forkJoinPool = new ForkJoinPool();
    public static String fileName = "D:\\maven\\repository";


    private static class FileSizeFinder extends RecursiveTask<Long> {
        final File file;

        public FileSizeFinder(final File theFile) {
            file = theFile;
        }

        @Override
        public Long compute() {
            long size = 0;
            if (file.isFile()) {
                size = file.length();
            } else {
                final File[] children = file.listFiles();
                if (children != null) {
                    List<ForkJoinTask<Long>> tasks = new ArrayList<ForkJoinTask<Long>>();
                    for (final File child : children) {
                        if (child.isFile()) {
                            size += child.length();
                        } else {
                            tasks.add(new FileSizeFinder(child));
                        }
                    }
                    for (final ForkJoinTask<Long> task : invokeAll(tasks)) {
                        size += task.join();
                    }
                }
            }
            return size;
        }
    }

    //1178349451 字节
    public static void main(final String[] args) throws IOException {
//        final long start2 = System.nanoTime();
//        Collection<File> files = FileUtils.listFiles(new File("D:\\maven\\repository"), null, true);
//        final long end2 = System.nanoTime();
//        long count = 0;
//        for (File file : files) {
//            if (!file.isDirectory()) {
//                count += file.length();
//            }
//        }
//        System.out.println("2 Time taken: " + (end2 - start2) / 1.0e9);
//        System.out.println(count);
//        System.out.println("begin caculate ....");
//        final long start = System.nanoTime();
//        final long total = forkJoinPool.invoke(new FileSizeFinder(new File("D:\\maven\\repository")));
//        final long end = System.nanoTime();
//        System.out.println("Total Size: " + total);
//        System.out.println("Time taken: " + (end - start) / 1.0e9);
        File file = new File("d:\\huxingie\\test\\filetmp\\sss\\a.txt");
        File parentFile = file.getParentFile();
        if(!parentFile.exists()){
            parentFile.mkdirs();
        }
        if(!file.exists()){
            file.createNewFile();
        }
        String property = System.getProperty("user.dir");
        System.out.println(property);
    }

}

    